//
//  yuanxinplayer.m
//  yuanxinplayer
//
//  Created by 晏德智 on 2016/11/23.
//  Copyright © 2016年 晏德智. All rights reserved.
//

#import "YuanXinPlayer.h"
#import <IJKMediaFramework/IJKFFMoviePlayerController.h>

#if __has_include(<React/RCTBridgeModule.h>)
#import <React/RCTConvert.h>
#import <React/UIView+React.h>
#else
#import "RCTConvert.h"
#import "UIView+React.h"
#endif

@interface YuanXinPlayer() {
    BOOL _isLive;
}

@property (nonatomic, strong) IJKFFMoviePlayerController *player;

@end

@implementation YuanXinPlayer

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self configPlayer];
        _framedrop = 1;
    }
    
    return self;
}

- (void)configPlayer{
    
#ifdef DEBUG
    [IJKFFMoviePlayerController setLogReport:YES];
    [IJKFFMoviePlayerController setLogLevel:k_IJK_LOG_DEBUG];
#else
    [IJKFFMoviePlayerController setLogReport:NO];
    [IJKFFMoviePlayerController setLogLevel:k_IJK_LOG_INFO];
#endif
    
    [IJKFFMoviePlayerController checkIfFFmpegVersionMatch:YES];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
}

- (void)insertReactSubview:(UIView *)view atIndex:(NSInteger)atIndex
{
    [self insertSubview:view atIndex:atIndex + 1];
}

- (void)removeReactSubview:(UIView *)subview
{
    [subview removeFromSuperview];
}

- (void)removeFromSuperview
{
    [super removeFromSuperview];
}

- (void)reactSetFrame:(CGRect)frame {
    [super reactSetFrame:frame];
    
    /**
     * https://github.com/Bilibili/ijkplayer/issues/1818
     * https://github.com/Bilibili/ijkplayer/issues/3245
     * https://github.com/Bilibili/ijkplayer/issues/3154
     * https://github.com/Bilibili/ijkplayer/issues/2478
     * https://github.com/Bilibili/ijkplayer/blob/master/ijkmedia/ijkplayer/ff_ffplay_options.h
     * http://www.jianshu.com/p/a5cf04181f3d
     * https://github.com/Bilibili/ijkplayer/issues/1572
     * https://github.com/Bilibili/ijkplayer/issues/210
     * https://github.com/Bilibili/ijkplayer/issues/95
     *
     * https://github.com/Bilibili/ijkplayer/issues/1990
     * http://www.jianshu.com/p/d6a5d8756eec?utm_campaign=hugo&utm_medium=reader_share&utm_content=note&utm_source=qq
     */
    
    if(!_player){
        IJKFFOptions *ijkOptions = [IJKFFOptions optionsByDefault];
        // Set param
        [ijkOptions setFormatOptionIntValue:1024 * 16 forKey:@"probsize"];
        [ijkOptions setFormatOptionIntValue:50000 forKey:@"analyzeduration"];
        [ijkOptions setPlayerOptionIntValue:0 forKey:@"videotoolbox"];
        [ijkOptions setPlayerOptionIntValue:_framedrop forKey:@"framedrop"]; // 丢帧解决音视频不同步的问题
        [ijkOptions setCodecOptionIntValue:IJK_AVDISCARD_DEFAULT forKey:@"skip_loop_filter"];
        [ijkOptions setCodecOptionIntValue:IJK_AVDISCARD_DEFAULT forKey:@"skip_frame"];
        if (_isLive) {
            // Param for living
            [ijkOptions setPlayerOptionIntValue:3000 forKey:@"max_cached_duration"];   // 最大缓存大小是3秒，可以依据自己的需求修改
            [ijkOptions setPlayerOptionIntValue:1 forKey:@"infbuf"];  // 无限读
            [ijkOptions setPlayerOptionIntValue:0 forKey:@"packet-buffering"];  //  关闭播放器缓冲
        } else {
            // Param for playback
            [ijkOptions setPlayerOptionIntValue:0 forKey:@"max_cached_duration"];
            [ijkOptions setPlayerOptionIntValue:0 forKey:@"infbuf"];
            [ijkOptions setPlayerOptionIntValue:1 forKey:@"packet-buffering"];
        }
        
        if (self.url) {
            _player = [[IJKFFMoviePlayerController alloc] initWithContentURL:self.url withOptions:ijkOptions];
        } else if (self.localPath) {
            NSRange range = [self.localPath rangeOfString:@"mainbundle/"];
            NSURL *fileUrl = nil;
            if (range.location != NSNotFound) {
                NSString *fileFullName = [self.localPath substringFromIndex:range.location + range.length];
                /*
                if ([fileFullName componentsSeparatedByString:@"."].count == 2) {
                    NSString *fileName = [[fileFullName componentsSeparatedByString:@"."] firstObject];
                    NSString *fileExt = [[fileFullName componentsSeparatedByString:@"."] lastObject];
                    fileUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:fileExt]];
                } else {
                    fileUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileFullName ofType:nil]];
                }
                */
                
                fileUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileFullName ofType:nil]];
            } else {
                fileUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingPathComponent:self.localPath]];
            }
            _player = [[IJKFFMoviePlayerController alloc] initWithContentURL:fileUrl withOptions:ijkOptions];
        }
        
        _player.view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        _player.view.frame = self.bounds;
        _player.scalingMode = IJKMPMovieScalingModeAspectFit;
        _player.shouldAutoplay = self.shouldAutoplay;
        [_player setPauseInBackground:YES];
        [self addSubview:_player.view];
        [self sendSubviewToBack:_player.view];
        //[self addSubview:self.mediaControl];
        //self.mediaControl.delegatePlayer = self.player;
        [self installMovieNotificationObservers];
        
        [_player prepareToPlay];
    }
}

- (void)setFramedrop:(int)framedrop {
    if (_player && framedrop >= -1) {
        _framedrop = framedrop;
        [_player setPlayerOptionIntValue:framedrop forKey:@"framedrop"];
    }
}

#pragma mark Install Movie Notifications

/* Register observers for the various movie object notifications. */
-(void)installMovieNotificationObservers
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loadStateDidChange:)
                                                 name:IJKMPMoviePlayerLoadStateDidChangeNotification
                                               object:_player];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackDidFinish:)
                                                 name:IJKMPMoviePlayerPlaybackDidFinishNotification
                                               object:_player];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(mediaIsPreparedToPlayDidChange:)
                                                 name:IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification
                                               object:_player];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackStateDidChange:)
                                                 name:IJKMPMoviePlayerPlaybackStateDidChangeNotification
                                               object:_player];
}

#pragma mark Remove Movie Notification Handlers

/* Remove the movie notification observers from the movie object. */
-(void)removeMovieNotificationObservers
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:IJKMPMoviePlayerLoadStateDidChangeNotification object:_player];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:IJKMPMoviePlayerPlaybackDidFinishNotification object:_player];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification object:_player];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:IJKMPMoviePlayerPlaybackStateDidChangeNotification object:_player];
}


- (void)loadStateDidChange:(NSNotification*)notification
{
    //    MPMovieLoadStateUnknown        = 0,
    //    MPMovieLoadStatePlayable       = 1 << 0,
    //    MPMovieLoadStatePlaythroughOK  = 1 << 1, // Playback will be automatically started in this state when shouldAutoplay is YES
    //    MPMovieLoadStateStalled        = 1 << 2, // Playback will be automatically paused in this state, if started
    
    IJKMPMovieLoadState loadState = _player.loadState;
    
    if ((loadState & IJKMPMovieLoadStatePlaythroughOK) != 0) {
        NSLog(@"loadStateDidChange: IJKMPMovieLoadStatePlaythroughOK: %d\n", (int)loadState);
    } else if ((loadState & IJKMPMovieLoadStateStalled) != 0) {
        NSLog(@"loadStateDidChange: IJKMPMovieLoadStateStalled: %d\n", (int)loadState);
    } else {
        NSLog(@"loadStateDidChange: ???: %d\n", (int)loadState);
    }
}

- (void)moviePlayBackDidFinish:(NSNotification*)notification
{
    //    MPMovieFinishReasonPlaybackEnded,
    //    MPMovieFinishReasonPlaybackError,
    //    MPMovieFinishReasonUserExited
    int reason = [[[notification userInfo] valueForKey:IJKMPMoviePlayerPlaybackDidFinishReasonUserInfoKey] intValue];
    
    switch (reason)
    {
        case IJKMPMovieFinishReasonPlaybackEnded:
            NSLog(@"playbackStateDidChange: IJKMPMovieFinishReasonPlaybackEnded: %d\n", reason);
            break;
            
        case IJKMPMovieFinishReasonUserExited:
            NSLog(@"playbackStateDidChange: IJKMPMovieFinishReasonUserExited: %d\n", reason);
            break;
            
        case IJKMPMovieFinishReasonPlaybackError:
            NSLog(@"playbackStateDidChange: IJKMPMovieFinishReasonPlaybackError: %d\n", reason);
            break;
            
        default:
            NSLog(@"playbackPlayBackDidFinish: ???: %d\n", reason);
            break;
    }
}

- (void)mediaIsPreparedToPlayDidChange:(NSNotification*)notification
{
    NSLog(@"mediaIsPreparedToPlayDidChange\n");
}

- (void)moviePlayBackStateDidChange:(NSNotification*)notification
{
    //    MPMoviePlaybackStateStopped,
    //    MPMoviePlaybackStatePlaying,
    //    MPMoviePlaybackStatePaused,
    //    MPMoviePlaybackStateInterrupted,
    //    MPMoviePlaybackStateSeekingForward,
    //    MPMoviePlaybackStateSeekingBackward
    
    if(_onPlayBackState){
        NSDictionary *event = @{
                                @"state": [[NSNumber numberWithInt:(int)_player.playbackState] stringValue],
                                };
        _onPlayBackState(event);
    }
    
    switch (_player.playbackState)
    {
        case IJKMPMoviePlaybackStateStopped: {
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: stoped", (int)_player.playbackState);
            break;
        }
        case IJKMPMoviePlaybackStatePlaying: {
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: playing", (int)_player.playbackState);
            break;
        }
        case IJKMPMoviePlaybackStatePaused: {
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: paused", (int)_player.playbackState);
            break;
        }
        case IJKMPMoviePlaybackStateInterrupted: {
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: interrupted", (int)_player.playbackState);
            break;
        }
        case IJKMPMoviePlaybackStateSeekingForward:
        case IJKMPMoviePlaybackStateSeekingBackward: {
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: seeking", (int)_player.playbackState);
            break;
        }
        default: {
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: unknown", (int)_player.playbackState);
            break;
        }
    }
}

- (void)resume
{
    if (_player) {
        [_player play];
    }
}

- (void)pause
{
    if (_player) {
        [_player pause];
    }
}

- (void)shutdown
{
    if (_player) {
        [_player shutdown];
    }
}

- (void)stop
{
    if (_player) {
        [_player stop];
    }
}

- (void)seekTo:(NSTimeInterval)currentPlaybackTime
{
    if (_player) {
        NSLog(@"(void)seekTo:(NSTimeInterval)currentPlaybackTime %f\n", currentPlaybackTime);
        _player.currentPlaybackTime = currentPlaybackTime;
    }
}

- (NSTimeInterval)getCurrentPlaybackTime {
    return _player.currentPlaybackTime;
}

- (void)prepare{
    if(_player){
        [_player prepareToPlay];
    }
}

- (void)play{
    if(_player){
        [_player play];
    }
}

@end
